import { eq } from "drizzle-orm";
import { db } from "../db";
import posts from "../db/schema/posts";

/**
 *
 * @returns  query posts
 */
export const getPosts = async (params?: { id?: number }) => {
  if (params?.id) {
    const result = await db.select().from(posts).where(eq(posts.id, params.id));
    return result[0];
  }
  const result = await db.select().from(posts);
  return result;
};

/**
 *
 * @param params post id and title
 * @returns created post
 */
export const createOrEditPost = async (params: { id?: number; title: string; content: string; ownerId: number, thumbimage: string, categoryId: number }) => {

  if (params.id) {
    return await db.update(posts).set({
      ...params,
      updated_at: new Date()
    }
    ).where(eq(posts.id, params.id));
  }
  return await db.insert(posts).values(params);
};

/**
 *
 * @param params post id
 * @returns deleted post
 */
export const deletePost = async (params: { id: number }) => {
  return await db.delete(posts).where(eq(posts.id, params.id));
};
